package com.xuecheng.manage_cms_client.service.impl;
import java.io.*;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.CmsSite;
import com.xuecheng.manage_cms_client.dao.CmsPageRepository;
import com.xuecheng.manage_cms_client.dao.CmsSiteRepository;
import com.xuecheng.manage_cms_client.service.CmsPageService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.util.Optional;

@Service
public class CmsPageServiceImpl implements CmsPageService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CmsPageServiceImpl.class);

    @Resource
    GridFsTemplate gridFsTemplate;

    @Resource
    GridFSBucket gridFSBucket;
    @Resource
    CmsPageRepository cmsPageRepository;
    @Resource
    CmsSiteRepository cmsSiteRepository;
    /**
     * 保存Html文件到服务器物理路径
     *
     * @param pageId 页面id
     */
    @Override
    public void savePageToServerPath(String pageId) {
        // 得到html文件的id,从CmsPage中获取HtmlFileID
        CmsPage cmsPage = this.findCmsPageById(pageId);
        String htmlFileId = cmsPage.getHtmlFileId();
        // 从GridFs中获取查询Html文件
        InputStream inputStream = this.getFileById(htmlFileId);
        if (inputStream == null) {
            LOGGER.error("根据CmsPage的HtmlFileId查询不到文件,HtmlId是" + htmlFileId);
            return;
        }
        // 得到站点信息
        String siteId = cmsPage.getSiteId();
        CmsSite site = this.findCmsSiteById(siteId);
        // 得到站点的物理路径
        String sitePhysicalPath = site.getSitePhysicalPath();

        // 得到页面的物理路径
        String pagePhysicalPath = sitePhysicalPath + cmsPage.getPagePhysicalPath() + cmsPage.getPageName();
        // 将Html文件保存再服务器物理路径上
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(new File(pagePhysicalPath));
            IOUtils.copy(inputStream, fileOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据CmsPage的Id查询一个CmsPage页面
     * @param pageId CmsPage的id
     * @return 查询出来的CmsPage对象
     */
    public CmsPage findCmsPageById(String pageId){
        Optional<CmsPage> optional = cmsPageRepository.findById(pageId);
        return optional.orElse(null);
    }

    /**
     * 根据文件ID从GridFs中查询文件
     * @param FileId 文件id
     * @return 输入流
     */
    private InputStream getFileById(String FileId){
        // 查找文件
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(FileId)));
        // 打开下载流
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        // 获取流
        GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
        try {
            return gridFsResource.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据SiteID查询一个站点
     * @param siteId Site的ID
     * @return Site对象
     */
    private CmsSite findCmsSiteById(String siteId){
        Optional<CmsSite> optional = cmsSiteRepository.findById(siteId);
        return optional.orElse(null);
    }
}
